package cn.miao.photoprinter.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import cn.miao.photoprinter.R;

import com.nostra13.universalimageloader.core.ImageLoader;

public class MyImageHorizalAdapter extends BaseAdapter {

    private LayoutInflater infalter;
    private ArrayList<String> paths = new ArrayList<String>();

    public MyImageHorizalAdapter(Context context) {
        infalter = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return paths.size();
    }

    @Override
    public String getItem(int position) {
        return paths.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void addAll(ArrayList<String> paths) {
        this.paths.clear();
        this.paths.addAll(paths);
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = infalter.inflate(R.layout.item_image_2, parent, false);
            holder = new ViewHolder();
            holder.iv_item = (ImageView) convertView.findViewById(R.id.iv_item);
            holder.tv_path = (TextView) convertView.findViewById(R.id.tv_path);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (position > paths.size() - 1) {
        	position = paths.size() - 1;
        }
        holder.tv_path.setText(paths.get(position));
//        Bitmap bitmap = getBitmapByPath(paths.get(position));
//        if (null == bitmap) {
//        	holder.iv_item.setImageResource(R.drawable.empty_photo);
//        } else {
//        	holder.iv_item.setImageBitmap(bitmap);
//        }
        // 
        ImageLoader.getInstance().displayImage("file://" + paths.get(position), holder.iv_item);
        return convertView;
    }
    
	private Bitmap getBitmapByPath(String path) {
		InputStream fis;
		try {
			fis = new FileInputStream(new File(path));
			Bitmap bmp = BitmapFactory.decodeStream(fis);
			return bmp;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}// 文件输入流
	}
    
    class ViewHolder {
        ImageView iv_item;
        TextView tv_path;
    }

}
